package library.and.xps.com.step.view.customview.WaveView;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewTreeObserver;

import java.util.Random;

import library.and.xps.com.step.util.AnimUtil;

public class WaveView extends BaseView implements ValueAnimator.AnimatorUpdateListener{

    private WavePice wavePiceFront  = null;

    public WaveView(Context context, AttributeSet attrs) {
        super(context, attrs);
        ValueAnimator animator = AnimUtil.getAnim(2000);
        animator.addUpdateListener(this);
        animator.start();
    }

    public WaveView(Context context) {
        super(context);
        ValueAnimator animator = AnimUtil.getAnim(4000);
        animator.addUpdateListener(this);
        animator.start();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int w = 0;
        int h = 0;
        if (widthMode == MeasureSpec.EXACTLY) {
            w = widthSize;
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            h = heightSize;
        }
        setMeasuredDimension(w, h);
    }

    @Override
    protected int getSensorType() {
        return Sensor.TYPE_GRAVITY;
    }

    @Override
    protected void drawSub(Canvas canvas) {
        wavePiceFront.draw(canvas);
    }

    @Override
    protected void logic() {

    }

    @Override
    protected void init() {
        if(isInEditMode())return;
        final Random r = new Random();
        int w = getMeasuredWidth();
        int h = getMeasuredHeight();
        wavePiceFront = new WavePice(r.nextInt(50),w,h);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
//        if(wavePiceFront==null)return;
//        wavePiceFront.SetX(event.values[1]);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        if(wavePiceFront==null)return;
        float f = ((RPoint)animation.getAnimatedValue()).getY();
        wavePiceFront.SetY(f);
    }
}
